﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BattleShips.Common;

namespace BattleShips.GameClients {
    class GameResponseParser {
        public Response Parse(string input) {
            //@<{comanda}:{errorCode}> [{payload}]

            Response response = new Response();
            if (input.StartsWith("@<")) {
                int indexOfSpace = input.IndexOf(' ');
                if (indexOfSpace == -1) {
                    indexOfSpace = input.Length - 1;
                    input = input.TrimEnd(';');
                } else {
                    response.Payload = input.Substring(indexOfSpace).TrimEnd(';');
                }
                string fullCommand = input.Substring(1, indexOfSpace);
                if (fullCommand.EndsWith(";")) {
                    fullCommand = fullCommand.TrimEnd(';');
                } else {
                    fullCommand = fullCommand.Trim();
                }
                if (fullCommand.StartsWith("<") && fullCommand.EndsWith(">")) {
                    string[] parts = fullCommand.Substring(1, fullCommand.Length - 2).Split(':');
                    if (parts.Length == 2) {
                        response.CommandName = parts[0];
                        response.Code = Convert.ToInt32(parts[1]);
                    } else {
                        response.CommandName = parts[0];
                    }
                } else {
                    throw new ParseException("Comanda trebuie sa fie incadrata de < >.");
                }
            } else {
                throw new ParseException("Comanda trebuie sa inceapa cu @.");
            }
            return response;
        }
    }
}
